from django.db.models import Prefetch, Q, Count
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.absent.models import Absent
from apps.absent.serializers import AbsentSerializer
from apps.inform.models import Inform, InformRead
from apps.inform.serializers import InformSerializer
from apps.oaauth.models import OADepartment
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator



## 获取最新通知
class LatestInformView(APIView):
    '''
    使用 类缓存 返回最新的 10条通知
    '''
    @method_decorator(cache_page(60*15))
    def get(self,request):
        current_user = request.user

        ## 返回公共的 或者 自己所在部门内的通知
        infroms = Inform.objects.prefetch_related(Prefetch('reads',queryset=InformRead.objects.filter(user_id=current_user.uid)),
                                                  'department').filter(Q(public=True) | Q(department=current_user.department))[:10]
        serializer = InformSerializer(infroms,many=True)
        return Response(serializer.data)


## 获取最新考勤信息
class LatestAbsentView(APIView):
    @method_decorator(cache_page(60*15))
    def get(self,request):
        ## 董事会可以看到所有人的考勤 非董事会只能看到自己的考勤
        current_user = request.user
        queryset = Absent.objects
        if current_user.department.name !="董事会":
            queryset = queryset.filter(request__department_id=current_user.department_id)
        queryset = queryset.all()[:10]
        serializer = AbsentSerializer(queryset, many=True)
        return Response(serializer.data)

### 获取部门总数
class DepartmentStaffCountView(APIView):
    @method_decorator(cache_page(60*15))
    def get(self,request):
        row = OADepartment.objects.annotate(staff_count=Count('staffs')).values("name","staff_count")
        print(f"row is ======= {row}")
        print("----"*6)
        return Response(row)


## API 的健康检查
class HealthCheckView(APIView):
    def get(self,request):
        return Response({"code":200})

